package com.cyys.modules.system.service.org;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cyys.common.dataScope.DataScope;
import com.cyys.common.ql.AR;
import com.cyys.common.services.CyysBaseService;
import com.cyys.common.utils.StringUtil;
import com.cyys.modules.core.model.TreeBuilder;
import com.cyys.modules.core.sysParam.OrgUtil;
import com.cyys.modules.system.dao.org.OrgDao;
import com.cyys.modules.system.model.org.Org;
import com.cyys.modules.system.model.org.OrgBranch;
import lombok.AllArgsConstructor;
import org.apache.commons.compress.utils.Lists;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

@Service("orgService")
@Transactional(readOnly = true)
@AllArgsConstructor
public class OrgService extends CyysBaseService<OrgDao, Org> {

	OrgBranchService orgBranchService;

	@Transactional(readOnly = false)
	public AR save(Org org) {
		if (StringUtil.isBlank(org.getId())) {
			if (StringUtil.isBlank(org.getParentId()) || org.getParentId().equals("0")) { // 保存根节点
				org.setParentId("0");
				org.setLevel("1");
			} else {
				Org parentOrg = dao.selectById(org.getParentId());
				// 修改父类的属性
				parentOrg.setHasChild(1); // 设置有子类
				dao.updateById(parentOrg);
			}
			org.setHasChild(0);
			dao.insert(org);
			orgBranchService.insertOrgBranch(org);
			OrgUtil.add(org);
			return AR.ok(org,"新增机构成功");
		} else {
			Org old= dao.selectById(org.getId());
			dao.updateById(org);
			//父节点修改需要更新父节点列表
			if(!(old.getParentId()).equals(org.getParentId())){
				// 更新部门关系
				OrgBranch orgBranch = new OrgBranch();
				orgBranch.setParentId(org.getParentId());
				orgBranch.setOrgId(org.getId());
				orgBranchService.updateOrgBranch(orgBranch);
			}
			OrgUtil.modify(org);
			return AR.ok("修改机构成功");
		}
	}

	@Transactional(readOnly = false)
	public AR deleteById(String id) {
		if (StringUtil.isBlank(id)) {
			return AR.failed("ID为空");
		}
		Org org = dao.selectById(id);
		if (dao.chlidNum(id) > 0) {
			return AR.failed("有子元素，不允许删除");
		}
		dao.deleteById(id); //此句要放在修改父类hasChild属性前面
		// 修改父类属性
		if (StringUtil.isNotBlank(org.getParentId())) {
			Org parentOrg = dao.selectById(org.getParentId());
			if (dao.chlidNum(org.getParentId()) == 0) {
				parentOrg.setHasChild(0);
				dao.updateById(parentOrg);
			}
		}
		//更新父节点列表(因为删除只允许删除无子节点的机构，所以此处只要删除关系表中orgId=删除的机构ID即可)
		orgBranchService.deleteAllOrgBranch(new String[]{id});
		OrgUtil.init(this);
		return AR.ok("删除成功");
	}

	@Transactional(readOnly = false)
	public AR deleteByIds(String ids)  {
		if (StringUtil.isBlank(ids)) {
			return AR.failed("ID为空");
		}
		String[] idList = ids.split(",");
		// 检查批量删除数据是否存在问题
		List<Org> orgList = dao.listByIds(idList);
		for (Org org : orgList) {
			if (dao.chlidNum(org.getId()) > 0) {
				return AR.failed("有子元素，不允许删除");
			}
		}
		dao.deleteBatchIds(Arrays.asList(idList)); //此句要放在修改父类hasChild属性前面
		for (Org org : orgList) {
			// 修改父类属性
			if (StringUtil.isNotBlank(org.getParentId())) {
				Org parentOrg = dao.selectById(org.getParentId());
				int parentCount = dao.chlidNum(org.getParentId());
				if (parentCount == 0) {
					parentOrg.setHasChild(0);
					dao.updateById(parentOrg);
				}
			}
		}
		//更新父节点列表(因为删除只允许删除无子节点的机构，所以此处只要删除关系表中orgId=删除的机构ID即可)
		orgBranchService.deleteAllOrgBranch(idList);
		OrgUtil.init(this);
		return AR.ok("删除成功");
	}

	public List<Org> listByParentId(String parentId)  {
		if (parentId == null) {
			List<Org> list = dao.getByParentId(null);
			List<Org> returnList = getChlid(list);
			return returnList;
		} else {
			List<Org> list = dao.getByParentId(parentId);
			List<Org> returnList = getChlid(list);
			return returnList;
		}
	}

	private List<Org> getChlid(List<Org> list)  {
		List<Org> returnList = Lists.newArrayList();
		for (Org org : list) {
			List<Org> childrenList = dao.getByParentId(org.getId());
			if (childrenList != null && childrenList.size() > 0) {
				org.setChildren(childrenList);
				getChlid(childrenList);
			}
			returnList.add(org);
		}
		return returnList;
	}


	public List<Org> listAllTree(QueryWrapper qw)  {
		DataScope dataScope= new DataScope();
		dataScope.setScopeName("id");
		return TreeBuilder.buildByRecursive(dao.selectListByScope(qw, dataScope));
	}

}
